package com.apps.ftapp.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.apps.ftapp.R;
import com.apps.ftapp.adapter.Singleton;
import com.apps.ftapp.bean.ExamOption;
import com.apps.ftapp.bean.ExamQuestion;
import com.apps.ftapp.bean.QuestionEntry;
import com.apps.ftapp.fragment.ExamMaterialFragment;
import com.apps.ftapp.fragment.ExamMultiSelectFragment;
import com.apps.ftapp.fragment.ExamRadioFragment;
import com.apps.ftapp.model.TikuLianxi;
import com.apps.ftapp.ui.IExamResponseListener;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.ScreenUtils;
import com.apps.ftapp.util.StatusBarUtils;
import com.apps.ftapp.util.Tools;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zzhoujay.richtext.ImageHolder;
import com.zzhoujay.richtext.RichText;
import com.zzhoujay.richtext.callback.ImageFixCallback;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cz.msebera.android.httpclient.Header;
import es.dmoral.toasty.Toasty;
import me.shaohui.bottomdialog.BottomDialog;

/**
 * 题库练习tiku/show
 */
public class SubjectZdTkuActivity extends FragmentActivity implements IExamResponseListener, View.OnClickListener {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.txt_timer)
    TextView txtTimer;
    @BindView(R.id.fenxiang)
    ImageView fenxiang;
    @BindView(R.id.shoucang)
    ImageView shoucang;
    @BindView(R.id.timu)
    ImageView timu;
    @BindView(R.id.gengduo)
    RelativeLayout gengduo;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.viewPager)
    ViewPager mViewPager;
    @BindView(R.id.jiexidaan)
    TextView jiexidaan;

    private TikuLianxi result = new TikuLianxi();


    String[] typeKey = {"single_choice", "choice", "uncertain_choice", "fill", "determine", "essay", "material", "lunshu", "mingci", "bianxi", "jiaoxue", "huodong", "xiezuo", "yuedu"};

    String[] typeName = {"单选题", "多选题", "不定项选择题", "填空题", "判断题", "问答题", "材料分析", "论述", "名词解释", "辨析", "教学设计", "活动设计", "写作", "阅读理解"};

    private String keys;
    private int keycur = 0;

    final Gson gson = new Gson();
    private String id;

    private String questionID;//当前题目ID

    Singleton singleton = Singleton.getInstance();

    private List<ExamQuestion> mQuestion = new ArrayList<>();

    ViewPagerAdapter mViewPagerAdapter;

    int screen_width;
    private int cur = 0;

    private String lmname;//data.put("lmname",lmname);;
    private String cccccc;

    private long baseTimer;

    private static boolean misScrolled = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subject_zd_tku);

        ButterKnife.bind(this);

        ShareSDK.initSDK(this);

        StatusBarUtil.setColor(SubjectZdTkuActivity.this, Color.WHITE, 1);
        StatusBarUtils.StatusBarLightMode(this);

        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        id = bundle.getString("id");
        keys = bundle.getString("keys");
        keycur = bundle.getInt("keycur");
        lmname = bundle.getString("lmname");
        cccccc = bundle.getString("cccccc");
//        initView();
        L.i("main", "----------------------111111111---------------" + id);
        loadData(id);

//
//                Timer timer = new Timer(txtTimer);
//        timer.start(txtTimer);

        screen_width = ScreenUtils.getScreenWidth(getApplicationContext()) - getResources().getDimensionPixelSize(R.dimen.fab_margin) * 2;
        imgBack.setOnClickListener(this);
        shoucang.setOnClickListener(this);
        timu.setOnClickListener(this);
        jiexidaan.setOnClickListener(this);
        fenxiang.setOnClickListener(this);
//        jx.setOnClickListener(this);
//        timu.setVisibility(View.GONE);
//        txtTimer.setVisibility(View.GONE);
//        shoucang.setVisibility(View.GONE);

        Handler myhandler = new Handler() {
            public void handleMessage(android.os.Message msg) {
                if (0 == baseTimer) {
                    baseTimer = SystemClock.elapsedRealtime();
                }

                int time = (int) ((SystemClock.elapsedRealtime() - baseTimer) / 1000);
//                                String hh = new DecimalFormat("00").format(time / 3600);
                String mm = new DecimalFormat("00").format(time % 3600 / 60);
                String ss = new DecimalFormat("00").format(time % 60);
                if (null != txtTimer) {
                    txtTimer.setText(mm + ":" + ss);
                }
                sendMessageDelayed(Message.obtain(this, 0x0), 1000);
            }
        };
        myhandler.sendMessageDelayed(Message.obtain(myhandler, 0x0), 1000);


    }


    private void initView() {
        if (mQuestion != null && mQuestion.size() > 0)
            collectQuestion(mQuestion.get(cur).getCollection() == 1);
        mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mQuestion);
        mViewPager.setAdapter(mViewPagerAdapter);

//        ViewPagerUtils.setSliderTransformDuration(mViewPager, 300, new DecelerateInterpolator());
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                if(position==mQuestion.size()-1&&positionOffset==0.0&&positionOffsetPixels==0){
//                    L.i("main","onPageScrolled。。。。。。。。。"+position+"======"+positionOffset+"===="+positionOffsetPixels);
//                }

            }

            @Override
            public void onPageSelected(int position) {
                if (position == mQuestion.size()) {
                    L.i("main", "最后。。。。。。。。。" + position + "======" + mQuestion.size());
                    mViewPagerAdapter.notifyDataSetChanged();
                } else {
                    //更新收藏状态
//                    L
                    L.i("main", position + "====zdfsdf:::::::" + mQuestion.get(position).getCollection());
                    collectQuestion(mQuestion.get(position).getCollection() == 1);
                    cur = position;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager.SCROLL_STATE_DRAGGING:
                        misScrolled = false;
                        break;
                    case ViewPager.SCROLL_STATE_SETTLING:
                        misScrolled = true;
                        break;
                    case ViewPager.SCROLL_STATE_IDLE:
                        if (mViewPager.getCurrentItem() == mViewPager.getAdapter().getCount() - 1 && !misScrolled) {
                            L.i("main", "=====继续。。。。。");
                            ActivitySkipUtil.skipAnotherActivity(SubjectZdTkuActivity.this, GestureFilpSucActivity.class, false);
                        }
                        misScrolled = true;
                        break;
                }
            }
        });

//        关掉 右划 返回
//        disableSlideBack();
//
//        Arad.bus.register(this);
    }


    public void collectQuestion(boolean fill) {
        if (fill) {
            shoucang.setImageDrawable(getResources().getDrawable(R.drawable.f_lx_2_2));
        } else {
            shoucang.setImageDrawable(getResources().getDrawable(R.drawable.f_lx_2_1));
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                showpopup();
                break;
            case R.id.shoucang:

                sc();
                break;

            case R.id.timu:
                ActivitySkipUtil.skipAnotherActivity(SubjectZdTkuActivity.this, GestureFilpSucActivity.class, false);
                break;

            case R.id.jiexidaan:


                BottomDialog.create(getSupportFragmentManager())
                        .setViewListener(new BottomDialog.ViewListener() {      // 可以进行一些必要对View的操作
                            @Override
                            public void bindView(View v) {
                                // you can do bind view operation
                                TextView textView = v.findViewById(R.id.da);

                                TextView daan = v.findViewById(R.id.daan);

//                                if("0".equals(mQuestion.get(cur).getAnswer())){
//                                    textView.setText("A");
//                                }else if("1".equals(mQuestion.get(cur).getAnswer())){
//                                    textView.setText("B");
//                                }else if("2".equals(mQuestion.get(cur).getAnswer())){
//                                    textView.setText("C");
//                                }else{
//                                    textView.setText("D");
//                                }

                                if ("".equals(Tools.isNull(mQuestion.get(cur).getAnswer()))) {
                                    textView.setVisibility(View.GONE);
                                    daan.setVisibility(View.GONE);
                                } else {
                                    textView.setVisibility(View.VISIBLE);
                                    daan.setVisibility(View.VISIBLE);
                                    textView.setText(mQuestion.get(cur).getAnswer());
                                }

                                TextView jiexineirong = v.findViewById(R.id.jiexineirong);


                                RichText.fromHtml(mQuestion.get(cur).getAnalysis())
                                        .autoFix(false)
                                        .scaleType(ImageHolder.ScaleType.FIT_XY)
                                        .resetSize(true)
                                        .size(ImageHolder.WRAP_CONTENT, ImageHolder.WRAP_CONTENT)
                                        .fix(new ImageFixCallback() {
                                            @Override
                                            public void onInit(ImageHolder holder) {
                                            }

                                            @Override
                                            public void onLoading(ImageHolder holder) {
                                            }

                                            @Override
                                            public void onSizeReady(ImageHolder holder, int imageWidth, int imageHeight, ImageHolder.SizeHolder sizeHolder) {
                                            }

                                            @Override
                                            public void onImageReady(ImageHolder holder, int width, int height) {
                                                if (width * 2 > screen_width) {
                                                    holder.setWidth(screen_width);
                                                    holder.setHeight(height * 2 * screen_width / (width * 2));
                                                } else {
                                                    holder.setWidth(width * 2);
                                                    holder.setHeight(height * 2);
                                                }
                                            }

                                            @Override
                                            public void onFailure(ImageHolder holder, Exception e) {
                                            }
                                        })
                                        .into(jiexineirong);


//                                jiexineirong.setText(mQuestion.get(cur).getAnalysis());
//                                jiexineirong.loadData(mQuestion.get(cur).getAnalysis(), "text/html; charset=UTF-8", null);

                            }
                        })
                        .setHeight(ScreenUtils.getScreenHeight(getApplicationContext()) / 3)
                        .setLayoutRes(R.layout.jiexidaan)      // dialog layout
                        .show();
                break;

            case R.id.fenxiang:

                share();

                break;

        }
    }


    /**
     * 收藏
     */
    private void sc() {
        //判断是否收藏
        //
        L.i("main", mQuestion.get(cur).getCollection() + "kljkj>>>>>>" + cur + ">>>>" + mQuestion.get(cur).getStem());
        if (0 == mQuestion.get(cur).getCollection()) {
            L.i("main", "收藏。。。");
            RequestParams params = new RequestParams();
            params.put("token", Constant.token);
            params.put("userId", Constant.uid);
            params.put("question_id", result.getQuestion_list().get(cur).getId());
            params.put("targetType", "tiku");
            params.put("targetId", id);
            Async.post("question/favorite", params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    if (statusCode == 200) {
                        L.i("main", new String(responseBody));
                        try {
                            //请求成功
                            Map jsonBean = gson.fromJson(new String(responseBody), Map.class);
                            L.i("main", jsonBean.toString());
                            if (1 == Tools.isDoubleNull(jsonBean.get("success")) || 1.0 == Tools.isDoubleNull(jsonBean.get("success"))) {
                                Toasty.normal(getApplicationContext(), "收藏成功").show();
//                            shoucang.setImageDrawable(getResources().getDrawable(R.drawable.f_lx_2_2));
//                            result.getData().get(cur).setFavorite("1");
                                mQuestion.get(cur).setCollection(1);
                                L.i("main", ">>>" + cur);
                                collectQuestion(mQuestion.get(cur).getCollection() == 1);
                            } else {
                                mQuestion.get(cur).setCollection(0);
                                Toasty.normal(getApplicationContext(), Tools.isNull(jsonBean.get("error"))).show();
                            }
                        } catch (Exception e) {
                        }
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                }
            });
        } else {

            //取消收藏

            L.i("main", "取消收藏。。。");
            RequestParams params = new RequestParams();
            params.put("token", Constant.token);
            params.put("userId", Constant.uid);
            params.put("question_id", result.getQuestion_list().get(cur).getId());
            params.put("targetType", "tiku");
            params.put("targetId", id);
            Async.post("question/unfavorite", params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    if (statusCode == 200) {
                        L.i("main", new String(responseBody));
                        try {
                            //请求成功
                            Map jsonBean = gson.fromJson(new String(responseBody), Map.class);
                            L.i("main", jsonBean.toString());
                            if (1 == Tools.isDoubleNull(jsonBean.get("success")) || 1.0 == Tools.isDoubleNull(jsonBean.get("success"))) {
                                Toasty.normal(getApplicationContext(), "取消收藏").show();
//                            shoucang.setImageDrawable(getResources().getDrawable(R.drawable.f_lx_2_2));
//                            result.getData().get(cur).setFavorite("1");
                                mQuestion.get(cur).setCollection(0);
                                L.i("main", ">>>" + cur);
                                collectQuestion(mQuestion.get(cur).getCollection() == 1);
                            } else {
//                            mQuestion.get(cur).setCollection(0);
                                Toasty.normal(getApplicationContext(), Tools.isNull(jsonBean.get("error"))).show();
                            }
                        } catch (Exception e) {
                        }
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                }
            });

        }


    }

    /**
     * Viewpager 内容
     */
    private class ViewPagerAdapter extends FragmentPagerAdapter {
        //FragmentStatePagerAdapter 之前继承的
        List<ExamQuestion> mQuestionList;

        ViewPagerAdapter(FragmentManager fm, List<ExamQuestion> questionList) {
            super(fm);
            mQuestionList = questionList;
//            L.i("main",".,.,.,.,.,.,.,.,.,.,.,.,.,."+questionList.toString());
        }

        @Override
        public Fragment getItem(int position) {
            L.i("main", "第：" + position + "题");
            if (position == mQuestionList.size()) {
                //结束
                L.i("main", "结束.........");
//                ActivitySkipUtil.skipAnotherActivity(SubjectZdActivity.this, GestureFilpSucActivity.class, false);


//                return ;

//                return ExamPreviewFragment.newInstance(mTitle, mPresenter.getAnswerRecordJson(), mPresenter.getSeconds(), type);
            }
            ExamQuestion question = mQuestionList.get(position);

//            L.i("main",".,.,.,.,.,.,.,.,.,.,.,.,.,.");

            QuestionEntry entry = new QuestionEntry();
            entry.setExamQuestion(question);
            entry.setPosition(position);
            entry.setTitle(Tools.getType(question.getType()));
            entry.setCount(mQuestionList.size());
            entry.setExam_or_analysis(0);
            entry.setLmname(lmname);


            switch (question.getType()) {
                case 0://单选题
                    timu.setVisibility(View.VISIBLE);
                    return ExamRadioFragment.newInstance(entry, false);
                case 1://多选题
                    timu.setVisibility(View.VISIBLE);
                    return ExamMultiSelectFragment.newInstance(entry);
                case 2://不定项选择题
                    timu.setVisibility(View.VISIBLE);
                    return ExamMultiSelectFragment.newInstance(entry);
                //TODO 3
                case 3://填空题
                    timu.setVisibility(View.GONE);
                    return ExamMaterialFragment.newInstance(entry);
                case 4://判断题
                    timu.setVisibility(View.VISIBLE);
                    return ExamRadioFragment.newInstance(entry, false);
                case 5://问题题
                    timu.setVisibility(View.GONE);
                    return ExamMaterialFragment.newInstance(entry);
                case 6://材料题
                    timu.setVisibility(View.GONE);
                    return ExamMaterialFragment.newInstance(entry);

                default:
                    timu.setVisibility(View.GONE);
                    return ExamMaterialFragment.newInstance(entry);
            }

//            return ExamRadioFragment.newInstance(entry, false);
        }

        @Override
        public int getItemPosition(Object object) {
//            if (object instanceof ExamPreviewFragment) {
//                return POSITION_NONE;
//            }
            return super.getItemPosition(object);
        }

        @Override
        public int getCount() {
            return (mQuestionList == null || mQuestionList.size() == 0) ? 0 : mQuestionList.size();
        }
    }

    /*
      单选
     */
    @Override
    public void onRadio(String selectedId, int whichOne) {
        L.i(selectedId + ":我是第" + whichOne + "个题");
        ExamQuestion question = mQuestion.get(whichOne);
        boolean isCorrect = false;
        for (ExamOption option : question.getDataList()) {
            if (option.getIs_correct() == 1) {
                if (option.getId().equals(selectedId)) {
                    isCorrect = true;
                    break;
                }
            }
        }
        cur = whichOne;
        Singleton.getInstance().updDatiList(whichOne + 1, true);
        Singleton.getInstance().updateans(question.getId(), selectedId + "");//改的更新某一题的答案 后期和接口沟通 确定answer类型 多选同下

//        Map m = new HashMap();
//        m.put("id", question.getId());
//        m.put("ans", selectedId + "");
//        m.put("keys", question.getType());
//        singleton.addData(m);

        if (whichOne == mQuestion.size() - 1) {
            L.i("结束");
            ActivitySkipUtil.skipAnotherActivity(SubjectZdTkuActivity.this, GestureFilpSucActivity.class, false);

        } else {
            gotoNextPage(whichOne);
        }


//        mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setAnswer(selectedId);
//        mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setIsRealy(isCorrect ? 1 : 0);

//        gotoNextPage(whichOne);
    }

    /*
    多选
     */
    @Override
    public void onMutil(List<String> selectedID, int whichOne) {
        L.i(selectedID + ":我是第" + whichOne + "个题");
        if (selectedID.size() > 0) {
            boolean isCorrect = true;
            String _ids = "";
            for (int i = 0; i < selectedID.size(); i++) {
                if (i != selectedID.size() - 1) {
                    _ids += selectedID.get(i) + ",";
                } else {
                    _ids += selectedID.get(i);
                }
            }

            ExamQuestion question = mQuestion.get(whichOne);
            for (ExamOption option : question.getDataList()) {
                if (option.getIs_correct() == 0) {
                    if (_ids.contains(option.getId())) {
                        isCorrect = false;
                        break;
                    }
                }
            }

            cur = whichOne;
            Singleton.getInstance().updDatiList(whichOne + 1, true);

            Singleton.getInstance().updateans(question.getId(), _ids);

//            Map m = new HashMap();
//            m.put("id", question.getId());
//            m.put("ans", _ids + "");
//            singleton.addData(m);


//            mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setAnswer(_ids);
//            mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setIsRealy(isCorrect ? 1 : 0);
        } else {
//            mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setAnswer(null);
//            mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setIsRealy(2);
        }
    }


    /**
     * 执行下一个页面
     *
     * @param currentPosition 当前页
     */
    private void gotoNextPage(int currentPosition) {
        int nextPage = currentPosition + 1;
        if (nextPage < mQuestion.size() + 1) {
            mViewPager.setCurrentItem(nextPage, true);
        }
        if (nextPage == mQuestion.size()) {
            mViewPagerAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onJudge(String selectedId, int whichOne) {
        boolean isCorrect = false;
        ExamQuestion question = mQuestion.get(whichOne);

        for (ExamOption option : question.getDataList()) {
            if (option.getIs_correct() == 1) {
                if (option.getId().equals(selectedId)) {
                    isCorrect = true;
                    break;
                }
            }
        }

//        mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setAnswer(selectedId);
//        mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setIsRealy(isCorrect ? 1 : 0);

        gotoNextPage(whichOne);
    }


    private void loadData(String id) {

        singleton.clearDati();
        singleton.clear();
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("categoryId", id);
        params.put("type", Tools.isNull(keys));
        L.i("main", Constant.token + ":::" + id + "::::" + keys + ":::" + Constant.uid);
        Async.post("tiku/show", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody));

                    try {
                        result = gson.fromJson(new String(responseBody), TikuLianxi.class);
                    } catch (Exception e) {

                        L.i("main", "bmqab。。。");
                        Toasty.normal(getApplicationContext(), !"".equals(Tools.isNull(result.getError())) ? result.getError() : (result.getLmname() + "暂无此类型的练习题")).show();
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                        finish();

                    }


                    L.i("main", result.getSuccess() + ":::" + result.getError());
                    L.i("main", result.getQuestion_list() + "========");
                    if (result.getSuccess() == 1) {


                        if (null != result.getQuestion_list() && result.getQuestion_list().size() > 0) {

                        } else {
                            Toasty.normal(getApplicationContext(), result.getLmname() + "暂无此类型的练习题").show();
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            finish();
                        }
                        for (int i = 0; i < result.getQuestion_list().size(); i++) {
                            TikuLianxi.QuestionListBean d = result.getQuestion_list().get(i);
                            if ("".equals(Tools.isNull(questionID))) {
                                //
                                questionID = d.getId();
                            }
                            ExamQuestion ques = new ExamQuestion();
                            ques.setId(d.getId());
                            ques.setStem(d.getStem());
                            ques.setType(Tools.getType(Tools.isNull(d.getType())));
                            //                                ques.setDifficulty(Tools.isIntNull(d.getQuestion().getDifficulty()));
                            //                            ques.setCourseId(d.get());
                            ques.setqNo(0);
                            ques.setSource(0);
                            ques.setCollection(Tools.isIntNull(d.getFavorite()));
                            ques.setAnalysis(d.getAnalysis());
                            //                        MyErrorJieXiModel.ItemsBean.MetasBeanX q = d.getMetas();
                            int j = 0;

                            StringBuffer sb = new StringBuffer();
                            //                        L.i("main","....."+d);
                            if (null != d.getAnswer() && d.getAnswer().size() > 0) {

                                for (String ddd : d.getAnswer()) {
                                    //                                getdaan(d.getAnswer().get());
                                    sb.append(getdaan(ddd));
                                    sb.append(" ");
                                }

                            }
                            //                            getdaan(d.getAnswer().get())
                            //                            zhengque = Tools.isIntNull(d.getAnswer().get(0));
                            //                        }


                            ques.setAnswer(sb.toString() + "");

                            List<ExamOption> options = new ArrayList();
                            for (String str : d.getMetas().getChoices()) {
                                ExamOption opt = new ExamOption();
                                opt.setId(j + "");
                                opt.setContent(str);
                                //                            //正确答案
                                //                            if(zhengque==j){
                                //                                L.i("main","正确为：：："+zhengque);
                                //                                opt.setIs_correct(1);
                                //                            }
                                options.add(opt);
                                //
                                j++;
                            }
                            ques.setDataList(options);
                            //
                            //                        Personal personal = new Personal();
                            //                        personal.setDo_count(d.getPersonal().getDo_count());
                            //                        personal.setRight_count(d.getPersonal().getRight_count());
                            //                        personal.setWrong_count(d.getPersonal().getWrong_count()+"");
                            //                        ques.setPersonal(personal);
                            //
                            //                        All all = new All();
                            //                        all.setDo_count(d.getAll().getDo_count());
                            //                        all.setEasy_wrong(d.getAll().getEasy_wrong());
                            //                        all.setWrong_rate(d.getAll().getWrong_rate());

                            //                        ques.setAll(all);
                            //                        ques.setAnswer(d.getAnswer_compare());
                            //                        ques.setAnalysis(d.getQuestion().getAnalysis());

                            //ques.set/
                            Map tmap = new HashMap();
                            tmap.put("index", i + 1);
                            //                            tmap.put("name", Tools.delHTMLTag(q.getStem()));
                            tmap.put("is", false);
                            tmap.put("type", ques.getType());
                            singleton.addD(tmap);
                            //为不选择 报错修改的  后期需要和接口沟通 传什么参数
                            Map temp = new HashMap();
                            temp.put("id", ques.getId());
                            temp.put("ans", "99");
                            temp.put("keys", ques.getType());
                            singleton.addData(temp);


                            mQuestion.add(ques);
                        }
                        if ("".equals(Tools.isNull(cccccc))) {
                            lmname = Tools.isNull(result.getLmname()).replace("快速练习", "");
                        } else {
                            lmname = result.getLmname();
                        }

                        //                    L.i("main","mQuestionmQuestionmQuestion>>>>>"+mQuestion.size());
                        //                            mViewPagerAdapter.notifyDataSetChanged();
                        initView();
                        singleton.setStartTime(Tools.getTime1());
                        Singleton.setType("1");
                        singleton.setId(result.getTestResult().getId());
                        singleton.setKeys(Tools.isNull(keys));
                        singleton.setLmname(lmname);
                    } else {

                        Toasty.normal(getApplicationContext(), !"".equals(Tools.isNull(result.getError())) ? result.getError() : (result.getLmname() + "暂无此类型的练习题")).show();
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        finish();
                    }
                }
//
////
//                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });


    }

    /**
     * @param str
     * @return
     */
    private String getdaan(String str) {
        if ("0".equals(str)) {
            return "A";
        } else if ("1".equals(str)) {
            return "B";
        } else if ("2".equals(str)) {
            return "C";
        } else if ("3".equals(str)) {
            return "D";
        }

        return "";
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                showpopup();
                return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    private void showpopup() {

        new MaterialDialog.Builder(this)
                .title(R.string.title1)
                .content(R.string.content)
                .positiveText(R.string.agree)
                .positiveColor(Color.BLACK)
                .negativeColor(Color.BLACK)
                .negativeText(R.string.disagree)
                .onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.NEUTRAL) {
                        } else if (which == DialogAction.POSITIVE) {
                            finish();
//                          Toast.makeText(MainActivity.this, "同意" + dataChoose, Toast.LENGTH_LONG).show();
                        } else if (which == DialogAction.NEGATIVE) {
                        }

                    }
                })
                .show();
    }


    private void share() {

        L.i("main", "========share=============");
        TikuLianxi.QuestionListBean.ShareBean shareBean = result.getQuestion_list().get(cur).getShare();
        if (null != shareBean) {
            OnekeyShare oks = new OnekeyShare();
            oks.disableSSOWhenAuthorize();
            oks.setTitle(shareBean.getTitle());
            oks.setTitleUrl(shareBean.getUrl());
            oks.setText(shareBean.getTitle());
            oks.setImageUrl(shareBean.getImage());
            oks.setUrl(shareBean.getUrl());
            oks.setSite(shareBean.getTitle());
            oks.setSiteUrl(shareBean.getUrl());
            oks.show(SubjectZdTkuActivity.this);
        }
    }
}
